package y2018.date1024.shufaxinshang;

import com.lu.jdog.util.FileUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class DownloadTool {

    /**
     * url列表
     */
    private List<String> urList;
    /**
     * css选择器
     */
    private String css = "";
    /**
     * 目录。绝对路径
     */
    private String baseDir;
    /**
     * 文件基本名，添加01,02
     */
    private String baseName = "";
    /**
     * 标题。实际文件夹名称
     */
    private String title;

    private PageUtil pageUtil;

    public DownloadTool() {
        urList = new ArrayList<>();
    }

    public DownloadTool setCss(String css) {
        this.css = css;
        return this;
    }

    public DownloadTool setBaseDir(String baseDir) {
        this.baseDir = baseDir.replace("\\", "/");
        return this;
    }

    public String setBaseName(String baseName) {
        this.baseName = baseName;
        return baseName;
    }

    public DownloadTool setBaseUrl(String baseUrl) {
        pageUtil = PageUtil.newInstance(baseUrl);
        this.urList = pageUtil.getUrlList();

        return this;
    }

    public void start() {
        if (title == null) {
            title = pageUtil.getTitle();
        }
//		去掉特殊字符。文件名不能包含
        title = title.replaceAll("[\\/:*<>\"?|]", "");

        if (baseDir == null) {
            throw new Error("未能设置基本保存目录");
        }
        if (title == null) {
            throw new Error("未能设置保存目录,因为标题未设置或不能自动获取标题");
        }
        String dir = this.baseDir + "/" + title;

        File dirFile = new File(dir);
        dirFile.mkdirs();

        int num = 0;
        int fail = 0;
        for (int i = 0; i < urList.size(); i++) {

            String url = urList.get(i);
            System.err.println("page:" + url);
            try {
                Document document = Jsoup.connect(url).get();
                Elements els = document.select(css);
                for (int j = 0; j < els.size(); j++) {
                    num++;
                    String imgUrl = els.get(j).absUrl("src");

                    InputStream is = new URL(imgUrl).openStream();


                    int dotIndex = imgUrl.lastIndexOf(".");
                    if (dotIndex == -1) {
                        dotIndex = imgUrl.length();
                    }
                    String suffix = imgUrl.substring(dotIndex, imgUrl.length());

                    String numStr = num < 10 ? ("0" + num) : (num + "");

                    String fileName = baseName + numStr + suffix;
                    String path = dir + "/" + fileName;

//					打印
                    System.out.println("img:" + imgUrl + " file:" + fileName);

                    File file = new File(path);
                    FileOutputStream os = new FileOutputStream(file);
                    FileUtil.write(is, os);

                }

            } catch (IOException e) {
                fail++;
                e.printStackTrace();
            }

        }
        System.err.println("\n下载完成。共计：" + num + "  失败：" + fail);
        System.err.println("存储目录：" + dir);
    }


}
